package com.bluesky.android.activities;

import com.bluesky.android.newlove.R;
import java.io.File;
import java.util.List;

import net.robotmedia.acv.Constants;
import net.robotmedia.acv.ui.ACVDialogFactory;

import com.bluesky.android.utils.*;
import com.bluesky.android.webservice.MangaChapter;
import com.bluesky.android.webservice.MangaReaderService;
import com.bluesky.android.webservice.MangaStory;
import com.bluesky.android.webservice.MangaStoryDetail;
import net.robotmedia.acv.ui.ACVDialogFactory;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

public class MangaDetailActivity extends TabActivity {
	
	public static final String MANGA_URL_KEY = "mangaurlkey";
	private String mangaURL;
	private static ProgressDialog dialog;
	private Handler mHandler;
	private GetMangaDetailThread mangaDetailThread;
	private static MangaStoryDetail mangaStoryDetail;
	private boolean isUpdate = false;
	private MangaDB mangaDB;
	private MangaChapterAdapter mangaChapterAdapter;
	private String mangaURLTypeKey;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manga_detail);
		try{
			mangaURL = getResources().getString(R.string.manga_url);
			mangaURLTypeKey = getResources().getString(R.string.manga_url_type_key);
			mangaDB = new MangaDB(this); 
			mangaDB.open();
			
			if(mangaStoryDetail == null){
				List<MangaStory> mangaList = mangaDB.getAllMangaStory();
				if(mangaList.size() < 1){
					startGetDataMangaDetailThread();
				}else
				{	
					MangaStory mangaStory = null;
					for(int i=0;  i < mangaList.size(); i++ ){
						MangaStory mangaItem = mangaList.get(i);
						if(mangaItem != null){
							if( mangaItem.getLink().equals(mangaURL) )
							{							
								mangaStory = mangaList.get(i);
								break;
							}
						}
					}				
					if(mangaStory != null){
						mangaStoryDetail = new MangaStoryDetail(mangaStory);
						mangaStoryDetail.setListChapters(mangaDB.getAllChaptersByMangaId(mangaStoryDetail.getMangaId() ) );
						bindDataToControl();
					}
					else{
						startGetDataMangaDetailThread();
					}
						
					
				}
			}else
			{
				bindDataToControl();			
			}
			
			Button btnUpdate = (Button) findViewById(R.id.btnUpdate);
			btnUpdate.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(mangaStoryDetail != null){
						isUpdate = true;
					}
					startGetDataMangaDetailThread();
				}
			});
			
	        TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
	        tabHost.addTab(tabHost.newTabSpec("tab1")
	                .setIndicator("Info", getResources().getDrawable(R.drawable.info))
	                .setContent(R.id.tab1)
	                );
	        tabHost.addTab(tabHost.newTabSpec("tab2")
	                .setIndicator("Chapters", getResources().getDrawable(R.drawable.chapter_list))
	                .setContent(R.id.tab2));
	        mangaDB.close();
		}catch(Exception ex){
			
		}
		
		
        
	}
	@Override
	public void onResume(){
		super.onResume();
		
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return mangaDetailThread;
	}
	
	@Override
	public void onPause(){
		super.onPause();
		if(mHandler != null && mThreadWatcher!=null){
			mHandler.removeCallbacks(mThreadWatcher);
		}
		if(mangaDB!= null){
			mangaDB.close();
		}
		
	}
	
	private void startGetDataMangaDetailThread(){
		mHandler = new Handler();
		mHandler.post(mThreadWatcher);
		mangaDetailThread =(GetMangaDetailThread) getLastNonConfigurationInstance();
        if (mangaDetailThread == null) {
        	mangaDetailThread = new GetMangaDetailThread(this.mangaURLTypeKey, this.mangaURL);
        	mangaDetailThread.start();
        	 
        }       
        if(mangaDetailThread.isAlive())
        {
        	dialog = new ACVDialogFactory(MangaDetailActivity.this).createLoadProgressDialog();
        	dialog.setMessage("Get data from service...");
        	dialog.show();
        }
	}
	private void bindDataToControl(){
		ImageView mangaImage = (ImageView) findViewById(R.id.image);
		//get image on internal data storage {App_Path}/Manga/{Manga_ID}
		File imageMangaOnDisk = new File(getDir("MangaReader", MODE_PRIVATE), MangaUtility.md5(mangaStoryDetail.getLink() ) );
		if(imageMangaOnDisk.exists()){
			mangaImage.setImageBitmap(BitmapFactory.decodeFile(imageMangaOnDisk.getPath() ) );
		}else{
			Bitmap imageBitmap = MangaUtility.GetImageFromURL(mangaStoryDetail.getImageLink());
			if(imageBitmap!= null){
				mangaImage.setImageBitmap(imageBitmap);
				MangaUtility.saveBitmapToDisk(imageMangaOnDisk.getPath(), imageBitmap);
			}			
		}
		
		
		TextView tvTitle = (TextView) findViewById(R.id.title);
		tvTitle.setText(MangaUtility.unescape(mangaStoryDetail.getTitle()));
		TextView tvAuthor = (TextView) findViewById(R.id.author);
		tvAuthor.setText(String.format("Author: %s",  MangaUtility.unescape(mangaStoryDetail.getAuthor() ) ) );		
		TextView tvSummary = (TextView) findViewById(R.id.summary);
		tvSummary.setText(MangaUtility.unescape(mangaStoryDetail.getSummary()) );
		mangaChapterAdapter= new MangaChapterAdapter(this, mangaStoryDetail.getListChapters(), this);
		ListView lvChapters = (ListView) findViewById(R.id.listView1);
		
		lvChapters.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			  public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
//			    ListAdapter adp = (ListAdapter)parent.getAdapter();
//			    //lista.get(position);
//			    MangaChapter s = mangaStoryDetail.getListChapters().get(Integer.parseInt(adp.getItem(position).toString()));
			  }
			});			
		lvChapters.setAdapter(mangaChapterAdapter);
	}
	
	private void saveDataToDatabase(){
		if(mangaDetailThread.getMangaDetail() != null){
			mangaDB.open();
			if(isUpdate == false){
				mangaStoryDetail = mangaDetailThread.getMangaDetail();			
				int mangaId = mangaDB.InsertMangaStory(mangaStoryDetail);			
				int countChapters = mangaStoryDetail.getListChapters().size();			
				for(int i = countChapters; i > 0; i--){
					MangaChapter chapter = mangaStoryDetail.getListChapters().get(i-1);
					if(chapter!= null){
						chapter.setMangaId(mangaId);
						int chapterId = mangaDB.InsertMangaChapter(chapter);
						chapter.setChapterId(chapterId);
					}
					
				}
			}else{
				MangaStoryDetail newMangaStoryDetail = mangaDetailThread.getMangaDetail();
				int countCurrentChapter = mangaStoryDetail.getListChapters().size();
				int countNewChapter = newMangaStoryDetail.getListChapters().size();
				for(int i = 1; i <= countNewChapter - countCurrentChapter; i++){
					MangaChapter chapter = newMangaStoryDetail.getListChapters().get(countNewChapter-i);
					if(chapter != null){
						chapter.setMangaId(mangaStoryDetail.getMangaId());
						int chapterId = mangaDB.InsertMangaChapter(chapter);
						chapter.setChapterId(chapterId);
						mangaStoryDetail.getListChapters().add(0, chapter);
					}
					
				}			
				
			}
			mangaDB.close();
			bindDataToControl();
		}else
		{
			//result value from service is null
			Log.e(MangaUtility.MANGA_LOG_TAG, "result value from service is null");
		}
		
		
	}
	
	private Runnable mThreadWatcher = new Runnable() {
	    public void run() {
		    if(!mangaDetailThread.isAlive() )
		    {
		    	dialog.dismiss();		    	
		    	if(mangaDetailThread.getMangaDetail() != null)
		    	{		    		
		    		saveDataToDatabase();
		    	}
		    	else{
		    		Log.e(MangaUtility.MANGA_LOG_TAG, "Result value from service is fail");
		    	}
		    }
		    else
		    {
		    	mHandler.postDelayed(this, 50);
		    }
		}
	 };
	
	
	private static class GetMangaDetailThread extends Thread{
		private String mangaUrl;
		private String mangaURLTypeKey;
		private MangaStoryDetail mangaDetail;
		
		public MangaStoryDetail getMangaDetail(){
			return mangaDetail;
		}
		
		public GetMangaDetailThread(String mangaURLTypeKey, String mangaUrl){
			this.mangaUrl = mangaUrl;
			this.mangaURLTypeKey = mangaURLTypeKey; 
		}
		

		private String getMangaUrl() {
			return mangaUrl;
		}

		private void setMangaUrl(String mangaUrl) {
			this.mangaUrl = mangaUrl;
		}
		
		public void run(){
			try {
				mangaDetail = MangaReaderService.getMangaStoryDetail(mangaURLTypeKey, mangaUrl);
			}catch (Exception e) {
				// TODO: handle exception
				
			}
		}

		public String getMangaURLTypeKey() {
			return mangaURLTypeKey;
		}

		public void setMangaURLTypeKey(String mangaURLTypeKey) {
			this.mangaURLTypeKey = mangaURLTypeKey;
		}
	}

}
